package com.zhouyibike.uu.ui.activity.yihoudong;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.entity.PayYiQuanResult;
import com.zhouyibike.uu.entity.PayYiQuanTypeResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.web.TotalWebActivity;
import com.zhouyibike.uu.ui.adapter.YiQuanChongZhiListAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.MyGridListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class YijuangounaiActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle, zhouyidanchehuodongxieyi,buyyiquanzongcount,zengyiquanzongcount,buyyiquanzongjiage;
    private YiQuanChongZhiListAdapter chongZhiListAdapter;
    private MyGridListView gv_list;
    private CheckBox cb_wx, cb_zfb;
    private String paytype = "1";
    private int chongzhiid;
    private Button btn_zhifu;
    private IWXAPI api;
    private String payamont;
    private boolean isformmaincz;
    private TextView tv_jian,tv_jia;
    private EditText et_numbershow;
    private int zrnum=1;//购买数量
    private double shijijineone=0;//一个订单金额
    private int goumaiyigenum=0;//该订单一个的数量
    private int goumaiyigezengsongnum=0;//该订单一个的赠送数量
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yijuangounai);
        api = WXAPIFactory.createWXAPI(this, null);
        EventBus.getDefault().register(this);
        initView();
        setbuyinfo();
        initListener();
    }

    private void initListener() {
        cb_wx.setOnCheckedChangeListener(this);
        cb_zfb.setOnCheckedChangeListener(this);
        zhouyidanchehuodongxieyi.setOnClickListener(this);
        tv_jia.setOnClickListener(this);
        tv_jian.setOnClickListener(this);
        et_numbershow.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (et_numbershow.getText().toString().length()<1)
                {
                    return;
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                    try {
//                        if (Integer.parseInt(s.toString()) < 1 || Integer.parseInt(s.toString()) > zrtotalnum) {
//                            et_numbershow.setText(zrnum + "");
//                            toastShow("输入的数量不在范围之内");
//                        } else {
//                            zrnum = Integer.parseInt(et_numbershow.getText().toString());
//                            et_numbershow.setSelection(s.length());//将光标移至文字末尾
//                            tv_zrnumber.setText(zrnum + "辆");
//                            tv_zrprice.setText(df.format(Double.parseDouble(bicyclePrice) * zrnum) + "元");
//                        }
//                    } catch (Exception e) {
//                        zrnum = 0;
//                        tv_zrnumber.setText(zrnum + "辆");
//                        tv_zrprice.setText(df.format(Double.parseDouble(bicyclePrice) * zrnum) + "元");
//                    }
                if (et_numbershow.getText().toString().length()<1||Integer.parseInt(et_numbershow.getText().toString())<0)
                {
                    tv_jian.setEnabled(false);
                    zrnum = 0;
                    et_numbershow.setSelection(s.length());//将光标移至文字末尾
//                    tv_zrnumber.setText(zrnum + "辆");
//                    tv_zrprice.setText(df.format(Double.parseDouble(bicyclePrice) * zrnum) + "元");
                }else{
                    tv_jia.setEnabled(true);
                    tv_jian.setEnabled(true);
                    zrnum = Integer.parseInt(et_numbershow.getText().toString());
                    if (zrnum==0)
                    {
                        tv_jian.setEnabled(false);
                    }
                    et_numbershow.setSelection(s.length());//将光标移至文字末尾
//                    tv_zrnumber.setText(zrnum + "辆");
//                    tv_zrprice.setText(df.format(Double.parseDouble(bicyclePrice) * zrnum) + "元");
                }
                datashuaxin();
            }
        });
    }

    private void initView() {
        et_numbershow= (EditText) findViewById(R.id.et_zr_numshow);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("翼券购买");
        mBtnBack.setOnClickListener(this);
        gv_list = (MyGridListView) findViewById(R.id.gv_chongzhi_list);
        cb_wx = (CheckBox) findViewById(R.id.cb_chongzhi_wx);
        cb_zfb = (CheckBox) findViewById(R.id.cb_chongzhi_zfb);
        btn_zhifu = (Button) findViewById(R.id.btn_chongzhiactivity_zhifu);
        btn_zhifu.setEnabled(true);
        btn_zhifu.setOnClickListener(this);
        zhouyidanchehuodongxieyi = (TextView) findViewById(R.id.zhouyidanchehuodongxieyi);
        tv_jian= (TextView) findViewById(R.id.tv_zr_jian);
        tv_jia= (TextView) findViewById(R.id.tv_zr_jia);
        buyyiquanzongcount= (TextView) findViewById(R.id.buyyiquanzongcount);
        zengyiquanzongcount= (TextView) findViewById(R.id.zengyiquanzongcount);
        buyyiquanzongjiage= (TextView) findViewById(R.id.buyyiquanzongjiage);
    }

    /**
     * //获取购买种类(规格)
     */
    private void setbuyinfo() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.PayYiQuanType(params),
                new ApiCallback<PayYiQuanTypeResult>() {

                    @Override
                    public void onSuccess(PayYiQuanTypeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            initList(model);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private void initList(PayYiQuanTypeResult model) {
        final List<PayYiQuanTypeResult.DataBean> list = new ArrayList<>();
        list.addAll(model.getData());
        chongZhiListAdapter = new YiQuanChongZhiListAdapter(this, list);
        gv_list.setAdapter(chongZhiListAdapter);
        gv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                shijijineone=list.get(position).getRealMoney();//一个订单金额
                goumaiyigenum=list.get(position).getPayCount();//该订单一个的数量
                goumaiyigezengsongnum=list.get(position).getGivenCount();//该订单一个的赠送数量
                TextView tv_amont = (TextView) view.findViewById(R.id.tv_itemchongzhi_p);
                payamont = tv_amont.getTag().toString();
                btn_zhifu.setEnabled(true);
                chongzhiid = Integer.parseInt(view.getTag().toString());
                chongZhiListAdapter.setpreid(chongzhiid);
                datashuaxin();
            }
        });
        if (list!=null&&list.size()>0)
        {
            chongzhiid=list.get(0).getId();
            shijijineone=list.get(0).getRealMoney();//一个订单金额
            goumaiyigenum=list.get(0).getPayCount();//该订单一个的数量
            goumaiyigezengsongnum=list.get(0).getGivenCount();//该订单一个的赠送数量
            chongZhiListAdapter.setpreid(chongzhiid);
            datashuaxin();
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_chongzhi_wx:
                if (isChecked) {
                    cb_zfb.setChecked(false);
                    paytype = "1";
                } else {
                    cb_zfb.setChecked(true);
                    paytype = "2";
                }
                break;
            case R.id.cb_chongzhi_zfb:
                if (isChecked) {
                    cb_wx.setChecked(false);
                    paytype = "2";
                } else {
                    cb_wx.setChecked(true);
                    paytype = "1";
                }
                break;

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.btn_chongzhiactivity_zhifu:
                chongzhi();
                break;
            case R.id.zhouyidanchehuodongxieyi:
                getWZMsg();
                break;
//            zhouyidanchehuodongxieyi
            case R.id.tv_zr_jian:
                if(zrnum==0){
                    //  toastShow("不能再少了");
                    tv_jian.setEnabled(false);
                }else
                {
                    zrnum--;
                    et_numbershow.setText(zrnum+"");
                    et_numbershow.setSelection(et_numbershow.getText().toString().length());//将光标移至文字末尾
//                    tv_zrnumber.setText(zrnum+"辆");
//                    tv_zrprice.setText(df.format(Double.parseDouble(bicyclePrice)*zrnum)+"元");
                }
                break;
            case R.id.tv_zr_jia:
//                if(zrnum==zrtotalnum){
//                    tv_jia.setEnabled(false);
//                    toastShow("不能再多了");
//                }else
            {
                zrnum++;
                et_numbershow.setText(zrnum+"");
                et_numbershow.setSelection(et_numbershow.getText().toString().length());//将光标移至文字末尾
//                tv_zrnumber.setText(zrnum+"辆");
//                tv_zrprice.setText(df.format(Double.parseDouble(bicyclePrice)*zrnum)+"元");
            }
            default:
                break;
        }
    }

    private void chongzhi() {
//        Map<String, String> params = new HashMap<>();
//        params.put("token", preferences.getString("token",""));
//        params.put("id",chongzhiid+"");
//        params.put("payType",paytype);
//        showProgressDialog();
//        addSubscription(apiStores.SaveRecharge(params),
//                new ApiCallback<PayForRegisterResult>() {
//
//                    @Override
//                    public void onSuccess(PayForRegisterResult model) {
//                        if(model.getStatus()== Config.SUCCESSCODE){
////                            paysuccess();
//                            if(paytype.equals("2")){//支付宝
//                                zfbpay(model.getData().getContent());
//                            }else{
//                                wxpay(model);
//                            }
//                        }else{
//                            toastShow(model.getMessage());
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(String msg) {
//                        toastShow(msg);
//
//                    }
//
//                    @Override
//                    public void onFinish() {
//                        dismissProgressDialog();
//                    }
//                });
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("typeId", chongzhiid + "");
        params.put("count", zrnum + "");
        showProgressDialog();
        addSubscription(apiStores.PayYiQuan(params),
                new ApiCallback<PayYiQuanResult>() {

                    @Override
                    public void onSuccess(PayYiQuanResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
//                            paysuccess();
                            if (paytype.equals("2")) {//支付宝

                                zfbpay(model.getData().getAlipay());
                            } else {
//                                model.getData().getWeChatPay();
//                                model.getData().getWeChat();
                                wxpay(model.getData().getWeChatPay());
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
//                        paysuccess();
//                        String zfb="\"app_id=2017041206669129&biz_content=%7B%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%22%E8%B4%AD%E4%B9%B0%E7%BF%BC%E5%88%B8%22%2C%22body%22%3A%22%E8%B4%AD%E4%B9%B0%E7%BF%BC%E5%88%B8%22%2C%22out_trade_no%22%3A%22ceb6a7d57b5a11e7ae1293349ff1e13c%22%7D&charset=utf-8&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F47.93.46.52%3A8765%2FPayment%2FAlipayCallBack&sign=PgzwsQl81CDxu%2Bo4oJUaoe6qGCGfC7esIDm2OTteeI5i5oGiI%2FRuu%2F5z2EbGsZvaTYzz74ZAF6IHEHqu4hoDEnDwiXp09Oaalh4PUOUOb77ga4vJ4%2Faw8qwc5TKmfm7J%2B%2BKqjjDEyerRNdk7TtLThr9NsH2d3LgrqcMpWiPrY9c%3D&sign_type=RSA&timestamp=2017-08-07+18%3A26%3A02&version=1.0\"";
//                        zfbpay(zfb);
                    }
                });
    }

    //    private void wxpay(PayForRegisterResult model){
//        api.registerApp( model.getData().getAppId());
//        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
//        if(!isPaySupported){
//            Toast.makeText(YijuangounaiActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        Toast.makeText(YijuangounaiActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
//        try{
//            PayReq request = new PayReq();
//
//            request.appId = model.getData().getAppId();
//
//            request.partnerId = model.getData().getPartnerId();
//
//            request.prepayId= model.getData().getPrepayId();
//
//            request.packageValue ="Sign=WXPay";
//
//            request.nonceStr= model.getData().getNoncestr();
//
//            request.timeStamp=model.getData().getTimestamp();
//
//            request.sign= model.getData().getSign();
//
//            api.sendReq(request);
//
//        }catch(Exception e){
//            Toast.makeText(YijuangounaiActivity.this, "异常："+e.getMessage(), Toast.LENGTH_SHORT).show();
//        }
//
//    }
    private void wxpay(PayYiQuanResult.DataBean.WeChatPayBean model) {
        api.registerApp(model.getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (!isPaySupported) {
            Toast.makeText(YijuangounaiActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(YijuangounaiActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try {
            PayReq request = new PayReq();

            request.appId = model.getAppId();

            request.partnerId = model.getPartnerId();

            request.prepayId = model.getPrepayId();

            request.packageValue = model.getPackageX();

            request.nonceStr = model.getNoncestr();

            request.timeStamp = model.getTimestamp();

            request.sign = model.getSign();

            api.sendReq(request);

        } catch (Exception e) {
            Toast.makeText(YijuangounaiActivity.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if (progress == 0) {//支付成功
            paysuccess();
        } else {
            Toast.makeText(YijuangounaiActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void zfbpay(final String orderinfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(YijuangounaiActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paysuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(YijuangounaiActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };
    private void getWZMsg(){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        params.put("type", "7");
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if(model.getStatus()== Config.SUCCESSCODE){
                            Intent i = new Intent(YijuangounaiActivity.this, TotalWebActivity.class);
                            i.putExtra("title","翼券服务协议");
                            i.putExtra("url",model.getData());
                            startActivity(i);
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    private void paysuccess() {
        Intent intent = new Intent(this, YiQuanbuyokActivity.class);
        startActivity(intent);
        setResult(1);
//        if (str.startsWith("yiquan3buyok")||str.startsWith("yiquan3sellok"))
        EventBus.getDefault().post("yiquan3buyok");
        finish();
//        intent.putExtra("payamont",payamont);
//        startActivityForResult(intent,400);

    }
    private void datashuaxin(){
        buyyiquanzongcount.setText((zrnum*goumaiyigenum)+"");
        zengyiquanzongcount.setText((zrnum*goumaiyigezengsongnum)+"");
        buyyiquanzongjiage.setText(String.format("%.2f",(zrnum*shijijineone)));
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
